package com.xiaoa.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 文件服务器
 *
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/test")
    public void test(HttpServletResponse response, String filePath)throws Exception{

        response.reset();

        String msg = "你好";
        File  file = new File(filePath);

        response.setContentType("application/octet-stream;charset=UTF-8");
        //解决中文文件名显示问题
        response.addHeader("Content-Disposition", "form-data; name=\"attachment\"; filename=\"" + new String(file.getName().getBytes("utf-8") , "iso-8859-1") + "\"");
        response.addHeader("Content-Length" , file.length() + "");

        InputStream  input = new FileInputStream(file);

        byte[] bs = new byte[1024];

        int readLength = 0;

        while ((readLength = input.read(bs)) != -1){

            response.getOutputStream().write(bs , 0 , readLength);
        }
        // test

        response.getOutputStream().flush();

    }

    /**
     * 下载文件
     * @param response
     * @param filePath
     * @throws Exception
     */
    @RequestMapping("/down")
    public ResponseEntity download(HttpServletResponse response, String filePath) throws Exception{
        File file = new File(filePath);
        byte[] body = FileUtils.readFileToByteArray(file);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file.getName());
        headers.setContentLength(body.length);

        return new ResponseEntity<byte[]>(body, headers,   HttpStatus.CREATED);
    }

}
